<template>
    <div class="page-pd">
        <el-tabs v-model="curTab">
            <el-tab-pane name="config" label="配置">
                <el-form label-width="120px" size="small">
                    <el-form-item label="appId:">
                        <auto-input v-model="appId"
                                    value-col="appId"
                                    text-col="name"
                                    :list="scenes"
                                    @change="changeScene"
                                    style="width:300px;box-shadow: 0 0 9px 0 #3a3"
                        ></auto-input>
                        <el-input v-model="appId" @change="changeForm" style="width:200px">
                        </el-input>
                    </el-form-item>
                    <el-form-item label="moduleId">
                        <el-input v-model="moduleId" style="width:300px">
                        </el-input>
                        <el-button @click="loadTextConfig" type="primary">加载</el-button>
                    </el-form-item>
                    <el-form-item label="终端">
                        <el-select v-model="terminal">
                            <el-option v-for="(v,t) in Terminals" :key="t" :value="v" :label="t">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="spId:">
                        <el-input v-model="spId"></el-input>
                    </el-form-item>
                    <el-form-item label="提交数据:">
                        <vue-json-editor v-model="dataPars" style="height:500px" :autoExpand="true"></vue-json-editor>
                        <!--<textarea-auto-height v-model="dataPars" rows="10"></textarea-auto-height>-->
                    </el-form-item>
                </el-form>
                <div class="t-center">
                    <el-checkbox v-model="isDefault">操作默认文案</el-checkbox>
                    <el-button @click="saveCfg" type="primary">新增文案</el-button>
                    <el-button @click="delCfg" type="primary">删除文案</el-button>
                </div>
            </el-tab-pane>
            <el-tab-pane name="dev" label="开发">
                贴入vue页面代码：(<code>用法举例：fgTexts.reorder || '调整排序'</code>)
                <el-input type="textarea" v-model="vueCode" :rows="10"></el-input>
                <el-button @click="makeTexts" type="primary">提取locales</el-button>
                <el-input type="textarea" v-model="resultCode" :rows="10"></el-input>
            </el-tab-pane>
        </el-tabs>
    </div>
</template>

<script>
import AutoInput from 'party_fe_component/src/components/auto-input';
import VueJsonEditor from '../components/vueJsonEditor/vueJsonEditor';
import Vue from 'vue'
import { Autocomplete } from 'element-ui'

Vue.use(Autocomplete)

export const Terminals = {
    PC: 0,
    APP: 1,
    Wechat: 2
}
export default {
    props: {},
    data() {
        return {
            curTab: 'config',

            dataPars: null,
            spId: this.$x.tokenUtil.spId,
            appId: this.$x.tokenUtil.appId,
            moduleId: this.$x.tokenUtil.moduleId,
            terminal: 0,
            isDefault: false,

            vueCode: '',
            resultCode: '',

            Terminals,

            scenes: [
                { name: '单位', appId: '741' },
                { name: '党组织', appId: '10645' },
                { name: '老干部', appId: '743' },
                { name: '党员', appId: '10643' },
                { name: '工作人员', appId: '10639' },
            ],
        };
    },
    created() {
        this.loadScenes()
        this.loadTextConfig()
    },
    methods: {
        changeScene() {
            if (this.appId) {
                this.changeForm()
                this.loadTextConfig()
            }
        },
        loadScenes() {
            var cfg = { byHeaders: { token: this.$x.tokenUtil.token } }
            var pars = {
                businessType: this.$x.tokenUtil.businessType,
                spId: this.spId,
                terminal: 0
            }
            this.$x.post('{abosEp}/portal/querySpMenus', pars, cfg).then(res => {
                var list = (res.data && res.data.menuList) || []
                var idMenus = list.reduce((all, m) => (all[m.srcId] = m, all), {})
                var scenes = []
                var hasSet = {}
                list.filter(m => m.parentId).map(m => {
                    var p = m
                    while ((p = idMenus[p.parentId])) {
                        m.name = p.name + ' / ' + m.name
                    }
                    if (m.url) {
                        var match = m.url && m.url.match(/moduleId=(\w+)/)
                        m.moduleId = match && match[1]
                        var key = m.appId + '.' + m.moduleId
                        if (!hasSet[key]) {
                            scenes.push(m)
                            hasSet[key] = 1
                        }
                    }
                })
                this.scenes = scenes
            })
        },
        changeForm() {
            this.$x.tokenUtil.appId = this.appId
            var scene = this.scenes.find(s => s.appId == this.appId)
            if (scene && scene.moduleId) {
                this.moduleId = scene.moduleId
                this.$x.tokenUtil.moduleId = scene.moduleId
            }
        },
        loadTextConfig() {
            var pars = {
                modelId: this.moduleId,
                terminal: Terminals.PC,
                appId: this.isDefault ? undefined : this.appId,
                spId: this.isDefault ? undefined : this.spId,
            }
            this.$x.get('{abos}/api/v61/doc/custom/scene', pars, { byHeaders: this.getHeaders() }).then(res => {
                var pages = (res.data && res.data.pages) || {}
                pages = Object.values(pages).map(dropEmpty).sort((a, b) => a.pageCode > b.pageCode ? 1 : -1)
                pages.map(pg => {
                    pg.locales = Object.values(pg.locales).map(dropEmpty).sort((a, b) => a.controlsCode > b.controlsCode ? 1 : -1)
                })

                if (pages.length === 0) {
                    pages = [{
                        pageCode: 'YOU_CODE',
                        pageName: '中文名',
                        // remark: null,
                        locales: []
                    }]
                }

                var data = {
                    modelId: this.moduleId,
                    terminal: this.terminal,
                    pages: pages,
                }

                this.dataPars = data

                function dropEmpty(obj) {
                    var r = {}
                    Object.keys(obj).map(key => {
                        if (obj[key]) r[key] = obj[key]
                    })
                    return r
                }
            })
        },
        saveCfg() {
            var pars = this.dataPars
            if (!this.checkData(pars)) return
            pars = {
                ...pars,
                appId: this.isDefault ? undefined : this.appId,
                spId: this.isDefault ? undefined : this.spId,
            }
            this.$x.post('{abos}/api/v61/doc/default/scene', pars, { byHeaders: this.getHeaders() })
                .then(res => {
                    this.$x.toast.success('OK')
                    sessionStorage.clear()
                })
        },
        getHeaders() {
            return {
                appId: this.isDefault ? undefined : this.appId,
                businessType: this.isDefault ? undefined : this.businessType,
                token: this.$x.tokenUtil.token
            }
        },
        checkData(pars) {
            var pageCode = isDup(pars.pages, pg => pg.pageCode)
            if (pageCode) {
                this.$x.toast.warning('pageCode 重复:' + pageCode)
                return
            }
            for (var i = 0; i < pars.pages.length; i++) {
                var pg = pars.pages[i]
                var controlsCode = isDup(pg.locales, locale => locale.controlsCode)
                if (controlsCode) {
                    this.$x.toast.warning('controlsCode 重复:' + controlsCode);
                    return
                }
            }
            return true

            function isDup(arr, getKey) {
                var map = {}
                for (var i = 0; i < arr.length; i++) {
                    var key = getKey(arr[i])
                    if (map[key]) {
                        return key
                    }
                    map[key] = 1
                }
            }
        },
        delCfg() {
            var url = `{abos}/api/v61/doc/default/scene?modelId=${this.moduleId}&terminal=${this.terminal}`
            if (this.isDefault) {
                url += `&appId=${this.appId}&spId=${this.spId}`
            }
            this.$x.delete(url, {}, { byHeaders: this.getHeaders() })
                .then(res => {
                    this.$x.toast.success('OK')
                })
                .catch(t => {
                    this.resultCode = `curl '${this.$x.axios.apiServers.abos}/api/v61/doc/default/scene?modelId=${this.moduleId}&terminal=${this.terminal}' -X DELETE `
                        + `-H 'businessType: ${this.$x.tokenUtil.businessType}' -H 'Accept: application/json, text/plain, */*' -H 'appId: ${this.$x.tokenUtil.appId}' `
                        + `-H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36' `
                        + `-H 'token: ${this.$x.tokenUtil.token}'`
                })
        },
        makeTexts() {
            var reg = /fgTexts\.(\w+)\s+\|\|\s+'(.+?)'/g
            var map = {}
            this.vueCode.replace(reg, (match, $1, $2) => {
                map[$1] = ({
                    controlsCode: $1,
                    name: $2,
                    // desabled: false,
                    // defaultValue: null,
                    // placeholder: null,
                    // checked: null,
                })
            })
            var locales = Object.values(map).sort((a, b) => a.controlsCode > b.controlsCode ? 1 : -1)
            this.resultCode = JSON.stringify(locales, null, 8)
        }
    },
    computed: {},
    components: { VueJsonEditor, AutoInput, }
}
</script>

<style lang="scss">
    textarea {
        font-family: "Courier";
        font-size: 13px;
    }
</style>
